package X20230510;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class two {
    private static Warehouse  warehouse= new Warehouse();
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.execute(new Store());
        executor.execute(new PickUp());
        executor.shutdown();

    }
    public static class Store implements Runnable{
        @Override
        public void run() {
            try{
                while (true){
                    warehouse.Store((int)(Math.random() * 100) + 1);
                    Thread.sleep(1000);
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
    public static class PickUp implements Runnable{
        @Override
        public void run() {
            while (true){
                warehouse.PickUp((int)(Math.random() * 100) + 1);
            }
        }
    }


    private static class Warehouse{
        private int capacity_max = 100;
        private int capacity;
        private static Lock lock = new ReentrantLock();
        private static Condition newDeposit = lock.newCondition();

        public int getCapacity() {
            return capacity;
        }

        public void Store(int amount)  {
            lock.lock();
            try {
                while (capacity==capacity_max){
                    System.out.println("存货" + amount + "\t\t现存" + getCapacity()+"\n\t\t存货失败，库存已满");
                    newDeposit.await();
                }
                capacity+=amount;
                System.out.println("存货"+amount+"\t\t现存"+getCapacity());
                newDeposit.signalAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
        public void PickUp(int amount){
            lock.lock();
            try {
                while (capacity < amount){
                    System.out.println("取货"+amount+"\t\t现存"+getCapacity()+"\n\t\t取货失败，库存不足");
                    newDeposit.await();
                }
                capacity-=amount;
                System.out.println("取货"+amount+"\t\t现存"+getCapacity());
                newDeposit.signalAll();
            }catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
}
